<template>
  <div class="ele-body">

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="deccId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          v-model:selection="selection"
          :scroll="{ x: 'max-content' }"
        >

          <!-- table上边工具栏 -->
          <template #toolbar>
            <a-space>
              <a-button type="primary" @click="restart()" :loading="restartLoading">
                <span>重启</span>
              </a-button>
              <a-button type="primary" @click="syncData()" :loading="syncDataLoading">
                <span>传感器数据同步</span>
              </a-button>
            </a-space>
          </template>

          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)">修改</a>
                <a-divider type="vertical" />
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
            <template v-if="column.key === 'onOffColumn'">
              <a-tag v-if="record.onOff == 1" color="green">开</a-tag>
              <a-tag v-else-if="record.onOff == 0" color="red">关</a-tag>
            </template>
            <template v-if="column.key === 'warnStatusColumn'">
              <a-tag v-if="record.warnStatus == 0" color="green">正常</a-tag>
              <a-tag v-else-if="record.warnStatus == 1 && record.channelType != 8" color="red">越下限</a-tag>
              <a-tag v-else-if="record.warnStatus == 1 && record.channelType == 8" color="red">探头坏</a-tag>
              <a-tag v-else-if="record.warnStatus == 2 && record.channelType != 8" color="red">越上限</a-tag>
              <a-tag v-else-if="record.warnStatus == 2 && record.channelType == 8" color="red">没获取到定位</a-tag>
              <a-tag v-else-if="record.warnStatus == 3" color="red">探头坏</a-tag>
              <a-tag v-else color="pick">未知</a-tag>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
  </div>

  <!-- 编辑弹窗 -->
  <device-env-control-channel-edit v-if="showEdit" v-model:visible="showEdit" :data="current" @done="reload"  />
</template>

<script>
import { DeviceEnvControlChannelApi } from '@/api/property/DeviceEnvControlChannelApi';
import DeviceEnvControlChannelEdit from './envcontrol-channel-edit.vue';
import { message } from 'ant-design-vue';
import { getEnvControlType } from '@/utils/device-property-util';
import {DeviceEnvControlQueueApi} from "@/api/property/DeviceEnvControlQueueApi";

export default {
  name: 'DeviceEnvControlChannel',
  components: {
    DeviceEnvControlChannelEdit
  },
  props: {
    data: Object
  },
  async mounted() {
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '传感器类型',
          dataIndex: 'channelType',
          customRender: function(row) {
            return getEnvControlType(row.text);
          }
        },
        {
          title: '第n路',
          dataIndex: 'channelPosition'
        },
        {
          title: 'AI的倍数',
          dataIndex: 'multiple'
        },
        {
          title: '传感器昵称',
          dataIndex: 'nickname'
        },
        {
          title: '开关',
          dataIndex: 'onOff',
          key : 'onOffColumn',
        },
        {
          title: '报警上阈值',
          dataIndex: 'highThreshold'
        },
        {
          title: '报警下阈值',
          dataIndex: 'lowThreshold'
        },
        {
          title: '报警连续检测时长',
          dataIndex: 'warnTime'
        },
        {
          title: '当时的值',
          dataIndex: 'value'
        },
        {
          title: '状态',
          dataIndex: 'warnStatus',
          key : 'warnStatusColumn',
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center',
        }
      ],
      // 表格搜索条件
      where: {"recordId" : this.data.recordId},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,

      restartLoading : false,
      restartTimer : undefined,

      syncDataLoading : false,
      syncDataTimer : undefined,
    };
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2022/08/28 08:12
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2022/08/28 08:12
     */
    reset() {
      this.where.recordId = this.data.recordId;
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2022/08/28 08:12
     */
    async remove(row) {
      const result = await DeviceEnvControlChannelApi.delete({ deccId: row.deccId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2022/08/28 08:12
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },

    restart() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        updateData: JSON.stringify({ old: {}, update: {}}),
        dictate : 2
      };
      let result = DeviceEnvControlQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.restartLoading = true; //转圈
          this.restartTimer = setInterval(this.checkRestartInterval, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

    syncData() {
      this.loading = true;
      let updateDataRecord = {
        recordId: this.data.recordId,
        updateData: JSON.stringify({ old: {}, update: {}}),
        dictate : 16
      };
      let result = DeviceEnvControlQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.syncDataLoading = true; //转圈
          this.syncDataTimer = setInterval(this.checkSyncDataInterval, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 获取表格数据
     *
     * @author fengshuonan
     * @date 2022/5/8 15:18
     */
    datasource({ page, limit, where, orders }) {
      return DeviceEnvControlChannelApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },

    clearSyncData(){
      this.syncDataLoading = false;
      clearInterval(this.syncDataTimer);
      this.syncDataTimer = null;
    },

    checkSyncDataInterval(){
      //let that = this;
      this.checkProcess(16, this.clearSyncData, function(){
        // 关闭弹框，通过控制visible的值，传递给父组件

      });
    },


    clearRestart(){
      this.restartLoading = false;
      clearInterval(this.restartTimer);
      this.restartTimer = null;
    },

    checkRestartInterval(){
      //let that = this;
      this.checkProcess(2, this.clearRestart, function(){

      });
    },

    checkProcess(dictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        dictate: dictate
      };
      let result = DeviceEnvControlQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.decqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },
  }
};
</script>
